import threading
from abc import ABC, abstractmethod


class BaseService(ABC):
    """所有后台服务的基类"""

    def __init__(self):
        self._thread = None
        self._running = False
        self._start_lock = threading.Lock()

    @abstractmethod
    def _run(self):
        """子类必须实现的核心逻辑"""
        pass

    def start(self):
        """线程安全的启动方法"""
        with self._start_lock:
            if self._running:
                return

            self._running = True
            self._thread = threading.Thread(
                target=self._run,
                daemon=True,
                name=f"{self.__class__.__name__}Thread"
            )
            self._thread.start()

    def stop(self):
        """停止服务"""
        self._running = False
        if self._thread and self._thread.is_alive():
            self._thread.join(timeout=5.0)